<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/7/12
 * @copyright PanxSoft Inc.
 */
namespace App\Services\Repositories;


use App\Models\OpenWechat\Authorizer;
use App\Models\OpenWechat\WechatTemplateNotice;
use App\Services\OpenWechat\AppFactory;
use App\Services\OpenWechat\CustomerTemplateNotice;

class WechatTemplateNoticeRepository
{
    protected $notice;

    public function __construct()
    {
        $this->notice = new WechatTemplateNotice;
    }
    
    /**
     * todo 暂时只支持IT / 消费品 行业 ，后面可能需要考虑其他行业
     *
     * @test
     *
     * @param Authorizer $authorizer
     *
     * @param string $template_id_short
     *
     * @return string
     *
     * @throws \App\Exceptions\ApiAbstractException
     */
    public function getAuthorizerTemplateId(Authorizer $authorizer, string $template_id_short): string
    {
        // 如果为IT行业，将消费品的short_id 转换成it行业的short_id
        $app = (new AppFactory)->authorizerApp($authorizer->authorizer_appid);

        if (CustomerTemplateNotice::isIndustryIt($app)) {
            $template_id_short = WechatTemplateNotice::CONSUMER_IT_MAP[$template_id_short];
        }

        $template = $this->notice
            ->where([
                'authorizer_id'     => $authorizer->id,
                'template_id_short' => $template_id_short,
            ])
            ->first(['template_id']);

        if($template) {
            return $template->template_id;
        }

        $template_id = CustomerTemplateNotice::addAndSaveTemplateId($authorizer, $template_id_short);

        return $template_id;
    }

}